var CONSOLE ={};
CONSOLE.lib = 'http://jupiterit.com/console/'

//Useful chomp function
String.prototype.chomp = function(str)             
{
    var index = this.lastIndexOf(str)
    if(index!= -1)
        return this.slice(0, index)
    else
        return this
}
//load prototype if you need to

if(typeof Prototype=='undefined')
{
	var script =document.createElement('script'); 
	script.setAttribute('language', 'javascript');
	script.setAttribute('src', CONSOLE.lib+'prototype.js');
	script.setAttribute('type', 'text/javascript');
	document.body.appendChild(script)
}
//load the css
var newCSS = document.createElement('link'); 
newCSS.setAttribute('rel', 'stylesheet');
newCSS.setAttribute('type', 'text/css');
newCSS.setAttribute('href', CONSOLE.lib+'console.css?' +(Math.random()*1000));
document.body.appendChild(newCSS);

//create element
CONSOLE.element = document.createElement('div'); 
CONSOLE.element.id = 'CONSOLE'
document.body.appendChild(CONSOLE.element)
CONSOLE.element.innerHTML = 
	"<div id='CONSOLE_title'>"+
		"<a href='#' onclick='CONSOLE.close()'>X</a>Jupiter JavaScript Console"+
	"</div>"+
	"<div id='CONSOLE_result'></div>"+
        "<input id='CONSOLE_code' onKeyUp='CONSOLE.input_key_press(this, event); return true;'>"+
    "<div id='CONSOLE_options'></div>"

/**
 * Positions the element
 */
CONSOLE.position = function() {
	var height, width;
	if(window.innerHeight){
		height = window.innerHeight;
		width= window.innerWidth;
	}
	else{
 		height= document.documentElement.clientHeight;
 		width= document.documentElement.clientWidth;
 	}
 	if(height == 0)
 		height = document.body.clientHeight;
 	if(width == 0)
 	{
 		width = document.body.clientWidth;
 		if( navigator.userAgent.match('MSIE') )
 		{
 			CONSOLE.element.style.width= width+'px';
 			document.getElementById('CONSOLE_result').style.width= width+'px';
 			document.getElementById('CONSOLE_title').style.width= width+'px';
 			document.getElementById('CONSOLE_code').style.width= (width-4)+'px';
 		}
 	}
 	if(navigator.userAgent.match('opera'))
 	{
 		document.getElementById('CONSOLE_code').style.width= (width-4)+'px'
 	}

 	var st = (document.body.scrollTop > document.documentElement.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop)
 	CONSOLE.element.style.top= (st  + height -241)+'px'
 	
}
CONSOLE.position();

/**
 * Closes the element
 */
CONSOLE.close = function() {
	$(CONSOLE.element).remove();
}

// Functionality for history

CONSOLE.command_array = new Array();
CONSOLE.command_position = -1;
CONSOLE.reset = function() {
    CONSOLE.command_position = -1;
}
CONSOLE.add_command = function(command){
    CONSOLE.command_array.unshift(command)
    CONSOLE.reset();
    if(CONSOLE.command_array.length > 30) CONSOLE.command_array.pop();
}
CONSOLE.get_previous = function(){
    if(CONSOLE.command_position >= CONSOLE.command_array.length) return CONSOLE.command_array[ CONSOLE.command_array.length - 1];
    
    if(CONSOLE.command_position < CONSOLE.command_array.length-1) CONSOLE.command_position++;
    
    var text  = CONSOLE.command_array[ CONSOLE.command_position];

    return text;
}
CONSOLE.get_next = function(){
    if(CONSOLE.command_position <= 0) return CONSOLE.command_array[0];
    
    if(CONSOLE.command_position > 0) CONSOLE.command_position--;
    
    var text  = CONSOLE.command_array[CONSOLE.command_position];
    
    return text;
}

/**
 * Run after enter is pressed
 */
_execute = function()
{
    
	CONSOLE.add_command($('CONSOLE_code').value)
    var html = '<p class="entered">>>'+$('CONSOLE_code').value+'<p>'
    try{
        var CONSOLE_result = eval($('CONSOLE_code').value) 
    }
    catch(e)
    {
        html += "<p> !>"+$H(e).inspect().escapeHTML()+"</p>"
        _last_error = e;
        CONSOLE.add_lines(html)
        return;
    }
    if(typeof  CONSOLE_result == 'undefined')
        html += "<p> =></p>"
    else if(typeof CONSOLE_result == 'string')
        html += "<p> =>"+CONSOLE_result.inspect().escapeHTML()+"</p>"
    else if(typeof CONSOLE_result == 'function'){
		//get function definition out of it
		var funct = 	CONSOLE_result.toString();
		html += "<p> => function "+funct.substring(8,funct.indexOf(')')+1 )+"</p>"
	}else if(CONSOLE_result.length){
        html += "<p> =>["
        
        $A(CONSOLE_result).each(function(item){  
            if(item.nodeName)
            	html+= item.nodeName+' element ,<br/>'
            else
            	html+= $H(item.toJSON()).inspect().escapeHTML()+',<br/>'
        })
        html = html.chomp(',<br/>')
        html += "]</p>"
    }else if(CONSOLE_result.inspect)
        html += "<p> =>"+$H(CONSOLE_result).inspect().escapeHTML()+"</p>"
    else
        html += "<p> =>"+CONSOLE_result.toString().escapeHTML()+"</p>"
        
    CONSOLE.add_lines(html)
    $("CONSOLE_code").value=""
}
/**
 * adds html to the CONSOLE
 */
CONSOLE.add_lines = function(html) {
    new Insertion.Bottom($('CONSOLE_result'), html);
    $('CONSOLE_result').scrollTop = $('CONSOLE_result').scrollHeight;
    $('CONSOLE_options').style.display = 'none'
}
/**
 * use crazy names so it doesn't conflict w/ eval
 * MZ up = 38
 * MZ down = 40
 */
CONSOLE.input_key_press = function(_el$, _event$)
{
    if(_event$.keyCode == 38) { //up
        _el$.value = CONSOLE.get_previous();
        return;
    }else if(_event$.keyCode == 40){
        _el$.value = CONSOLE.get_next();
        return;
    }else if(_event$.keyCode == 13) {
    	_execute();
    	return false;
    }
    
    var _text$ = _el$.value;
    //get text to where we are editing
    
    _text$= _text$.substring(0, CONSOLE.get_caret_pos($('CONSOLE_code')) );
 
    //find the last .
    
    var _last$ =0 ;
    _last$ = ( _text$.lastIndexOf('.') > _last$ ? _text$.lastIndexOf('.') : _last$ )
    
    //get last operator or space
    var _start$ =-1 ;
    _start$ = ( _text$.lastIndexOf(' ') > _start$ ? _text$.lastIndexOf(' ') : _start$ )
    _start$ = ( _text$.lastIndexOf('+') > _start$ ? _text$.lastIndexOf('+') : _start$ )
    _start$ = ( _text$.lastIndexOf('-') > _start$ ? _text$.lastIndexOf('-') : _start$ )
    _start$ = ( _text$.lastIndexOf('/') > _start$ ? _text$.lastIndexOf('/') : _start$ )
    _start$ = ( _text$.lastIndexOf('*') > _start$ ? _text$.lastIndexOf('*') : _start$ )
    
    _start$=_start$+1;
    CONSOLE.token = _text$.substring(_start$, _last$); //save token
    
    if(CONSOLE.token == '' || _start$ >= _last$  )
    {
        $('CONSOLE_options').style.display = 'none'
        return;
    }

    var _remainder$ = _text$.substring(_last$+1);
    _results$ =[];
    
    if(CONSOLE.token != CONSOLE.last_token) {
        try{
            CONSOLE.CONSOLE_result = eval(CONSOLE.token);
        }catch(e){
            $('CONSOLE_options').style.display = 'none';
            return;
        }
    }
    CONSOLE.last_token = CONSOLE.token;  //set as last token;
    
    for(var _thing$ in CONSOLE.CONSOLE_result)
    {
        if(_remainder$ != ''){
            if( _thing$.indexOf(_remainder$) === 0 )
                _results$.push( CONSOLE.create_option_html(_thing$, CONSOLE.CONSOLE_result )   )
        }
        else
            _results$.push( CONSOLE.create_option_html(_thing$, CONSOLE.CONSOLE_result )  )
    }
    $('CONSOLE_options').innerHTML = '<table><tr>'+_results$.sort().join('</tr><tr>')+'<tr></table>';
    $('CONSOLE_options').style.display = 'block'
}
CONSOLE.create_option_html = function(thing, aobject)
{
    try{
    return '<td>'+thing.escapeHTML()+'</td><td class="'+(typeof aobject[thing] )+'">'+(typeof aobject[thing] )+'</td>';
	}catch(e){
		
	return '<td>'+thing.escapeHTML()+'</td><td class="unknown">unknown</td>';
	}
}
CONSOLE.get_caret_pos = function(oField){

    var iCaretPos = 0;

    if (document.selection) { 
        oField.focus ();
        var oSel = document.selection.createRange ();
        oSel.moveStart ('character', -oField.value.length);
        iCaretPos = oSel.text.length;
    }
    else if(oField.selectionStart || oField.selectionStart == '0')
        iCaretPos = oField.selectionStart;
    return (iCaretPos);
}
